const axios = require('./axios');

let musicUrl = {}
axios({
  method: "get",
  url: url || 'https://hifini.com/thread-34298.htm',// 这个url通过get请求参数获取，参数名为url
})
  .then(function (res) {
    // console.log(``, res.status)
    if (res.status === 200) {
      let data = res.data;
      try {
        //  判断是否可非会员听歌
        if (!/id=\"player4\"/gims.exec(data)) {
          return musicUrl;
        };

        // 获取歌词
        let zz = /<h5>\s*?歌词\s*?<\/h5>(.*?)<h5>/gims.exec(data)
        zz = zz[1].replace(/<p>|<\/p>|<\/p>\s*?<p>/gims, ' ').trim()
        zz = zz.replace(/\s+/g, ' ')
        let gc = []
        zz.split(' ').forEach((item, index) => {
          gc.push(item.trim());
        })

        // 获取歌曲信息
        let musicUrl = {
          name: /title.*?\'(.*?)\',/g.exec(data)[1],
          artist: /author.*?\'(.*?)\',/g.exec(data)[1],
          // 获取url这样不行了，hifini有增加一个人机认证的过程，需要多一步来获取到对应的url，可以在tac_m_play.js文件中查看方法。
          // url: "https://hifini.com/" + /url.*?\'(.*?)\',/g.exec(data) ? /url.*?\'(.*?)\',/g.exec(data)[1] : /url.*?\'(.*?)\'/g.exec(data)[1] + generateParam(/generateParam\(\'(.*?)\'\),/g.exec(data)[1]),
          cover: /pic.*?\'(.*?)\'/g.exec(data)[1],
          lyric: gc, // 歌词
        }
        return musicUrl
      } catch (e) {
        return musicUrl
      }
    }
  })
  .catch(function (error) {
    return musicUrl
  });

/* 这里是php代码，给前端返回数据，数据就是 musicUrl */

// 获取歌曲信息需要的验证代码
function base32Encode(str) {
  var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
  var bits = ""; var base32 = "";
  for (var i = 0; i < str.length; i++) {
    var bit = str.charCodeAt(i).toString(2);
    while (bit.length < 8) { bit = "0" + bit; } bits += bit;
  }
  while (bits.length % 5 !== 0) { bits += "0"; }
  for (var j = 0; j < bits.length; j += 5) {
    var chunk = bits.substring(j, j + 5);
    base32 += base32chars[parseInt(chunk, 2)];
  }
  while (base32.length % 8 !== 0) { base32 += "="; }
  return base32.replace(/=/g, 'HiFiNiYINYUECICHANG');
}
// 获取歌曲信息需要的验证代码
function generateParam(data) {
  var key = '95wwwHiFiNicom27';
  var outText = '';
  for (var i = 0, j = 0; i < data.length; i++, j++) {
    if (j == key.length) j = 0;
    outText += String.fromCharCode(data.charCodeAt(i) ^ key.charCodeAt(j));
  }
  return base32Encode(outText);
}
